package com.kcht.sylyg08.utils;

import com.kcht.sylyg08.service.model.TagInfo;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;

/**
 *
 * @Package:        com.kcth.sylyg08.rest
 * @Description:    XML解析为TagInfo的工具类
 * @Author:         lenovo
 * @CreateDate:     2019/5/14 16:00
 */
public class XmlUtils {
    /** 解析XML文件 目前我不知道读一张卡的一个报文是不是只有一个message，所以我写了一个集合的，一个单个对象的 */
    public static List<TagInfo> parseXML(String message) {
        List<TagInfo> tags = new ArrayList<TagInfo>();
        ByteArrayInputStream byteArrayInputStream = null;
        try {
            SAXReader reader = new SAXReader();
            byteArrayInputStream = new ByteArrayInputStream(message.getBytes("UTF-8"));
            Document document = reader.read(byteArrayInputStream);
            List<Node> selectNodes = document.selectNodes("//member");
            for (Node node : selectNodes) {
                TagInfo tagInfo = new TagInfo();
                Element member = (Element) node;
                /** 资产编号 */
                String rawHex = member.element("rawHex").getText();
                /** 设置资产编号 */
                tagInfo.setEpc(rawHex);
                /** 获取extension标签 */
                Element extension = member.element("extension");
                String discoverLocation = extension.attribute("discoverLocation").getText();
                tagInfo.setDiscoverLocation(transLocation2(discoverLocation));
                String discoverTimestamp = extension.attributeValue("discoverTimestamp");
                Date discoveryTime = new Date(Long.parseLong(discoverTimestamp));
                tagInfo.setDiscoverTime(discoveryTime);
                tagInfo.setSightingCount(Integer.parseInt(extension.attributeValue("sightingCount")));
                Element fieldList = extension.element("fieldList");
                List<Element> fields = null;
                if (fieldList != null) {
                    fields = fieldList.elements("field");
                }
                if (fields != null && fields.size() > 0) {
                    for (Element field : fields) {
                        String name = field.elementText("name");
                        String value = field.elementText("value");
                        tagInfo.setMap(name, value);
                    }
                }
                tags.add(tagInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return tags;
    }


	/*public static TagInfo parseXML(String message){
		TagInfo tagInfo = new TagInfo();
		try{
			SAXReader reader = new SAXReader();
			//Document document = reader.read(message);
			Document document = reader.read(new ByteArrayInputStream(message.getBytes("UTF-8")));
			List<Node> selectNodes = document.selectNodes("//member");

				//System.out.println(node.getName());
				Element member = (Element) selectNodes.get(0);
				String rawHex = member.element("rawHex").getText();//资产编号
				tagInfo.setAssetId(rawHex);//设置资产编号
				Element extension = member.element("extension");//获取extension标签
				String discoverLocation = extension.attribute("discoverLocation").getText();
				tagInfo.setDiscoverLocation(transLocation2(discoverLocation));

				String discoverTimestamp = extension.attributeValue("discoverTimestamp");
				//将时间
				Date dicoveryTime = new Date(Long.parseLong(discoverTimestamp));
				tagInfo.setDiscoverTime(dicoveryTime);
				String sightingCount = extension.attributeValue("sightingCount");
				System.out.println(sightingCount);
				Element fieldList = extension.element("fieldList");
				List<Element> fields = null;
				if(fieldList != null){
					fields = fieldList.elements("field");
				}
				if(fields!=null && fields.size()>0){
					for (Element field : fields) {
						String name = field.elementText("name");
						String value = field.elementText("value");
						//System.out.println(name+":"+value);
						tagInfo.setMap(name, value);
					}
				}
				//System.out.println(tagInfo);
		}catch(Exception e){
			e.printStackTrace();
		}




		return tagInfo;
	}*/

    /**
     * 将discoverLocation中的英文转换为中文
     *
     * @param location
     * @return
     */
    public static String transLocation(String location) {
        String replaceLRName = location.replace("LRName", "逻辑阅读器");
        String replaceClass = replaceLRName.replace("Class", "阅读器类型");
        String replaceID = replaceClass.replace("ID", "阅读器ID");
        String replaceIP = replaceID.replace("IP", "阅读器IP");
        String replaceAnt = replaceIP.replace("Ant", "天线");
        String replaceProtocol = replaceAnt.replace("Protocol", "通讯协议");
        return replaceProtocol;
    }

    /**
     * 将转换后的discoverLocation分割，存放到Map中
     *
     * @param originLocation
     * @return
     */
    public static Map<String, String> transLocation2(String originLocation) {
        Map<String, String> map = new HashMap<>();
        //String location = transLocation(originLocation);
        String[] strs = originLocation.split(":");
        for (String string : strs) {
            /** System.out.println(string); */
            String name = string.substring(0, string.indexOf('['));
            String value = string.substring(string.indexOf('[') + 1, string.indexOf(']'));
            map.put(name, value);
        }

        return map;
    }

}
